<template>
  <el-dialog v-model="dialogVisible" title="新增" center width="500" append-to-body>
    <el-form ref="formInstall" :model="form" :disabled="isDetail" status-icon :rules="rules" label-position="left" label-width="auto">
      <el-form-item label="编号:" prop="id">
        <el-input v-model.trim="form.id" disabled placeholder="自动生成" />
      </el-form-item>
      <el-form-item label="专业名称:" prop="name">
        <el-input v-model.trim="form.name" placeholder="请输入专业名称" />
      </el-form-item>
      <el-form-item label="专业描述:" prop="des">
        <el-input v-model.trim="form.des" type="textarea" placeholder="请输入专业描述" />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="submit" v-if="!isDetail">确定</el-button>
        <el-button type="primary" @click="cancel"> 取消 </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { getDetailApi } from '@/api/major/index'

const dialogVisible = ref(false)

const isDetail = ref(false)
const open = async (id, type) => {
  isDetail.value = type == 'detail'
  if (id) {
    const res = await getDetailApi({ id })
    if (res.code == 200) {
      form.value = res.data
    } else {
      ElMessage.error(res.msg)
    }
  }
  dialogVisible.value = true
}

const formInstall = ref(null)
const form = ref({
  id: '',
  name: '',
  des: '',
})
const rules = reactive({
  name: [{ required: true, message: '请输入专业名称', trigger: 'blur' }],
  des: [{ required: true, message: '请输入专业描述', trigger: 'blur' }],
})

const submit = async () => {
  if (!formInstall.value) return
  formInstall.value.validate(async (valid) => {
    if (valid) {
      emit('submit', form.value)
      cancel()
    }
  })
}

const cancel = () => {
  dialogVisible.value = false
  form.value = {}
}

const rest = () => {
  formInstall.value.resetFields()
}

const emit = defineEmits(['submit'])
defineExpose({
  open,
})
</script>

<style scoped lang="scss"></style>
